<!--
 * @Author: your name
 * @Date: 2021-07-21 15:55:53
 * @LastEditTime: 2021-10-13 17:03:31
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \usp-osm-frondend\src\views\orderCenter\components\applyExchange.vue
-->
<template>
  <el-dialog
    :title="title"
    :visible.sync="isShow"
    v-if="isShow"
    width="50%"
    top="0"
    append-to-body
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :wrapperClosable="false"
    destroy-on-close
    center
    :before-close="handleClose"
  >
    <v-table ref="swapTable" :data="swapTableData" border>
      <el-table-column
        label="商品名称"
        align="center"
        min-width="80"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          {{ scope.row.spuName }}
        </template>
      </el-table-column>
      <el-table-column
        label="SKU Code"
        align="center"
        min-width="100"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          {{ scope.row.skuCode }}
        </template>
      </el-table-column>
      <el-table-column
        label="换货数量"
        align="center"
        min-width="100"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          {{ scope.row.quantity }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        min-width="120"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <el-select @change="resultsChange" v-model="scope.row.results" placeholder="请选择">
            <el-option
              v-for="item in lookupItems.RESULTAUDIT"
              :key="item.id"
              :label="item.dicName"
              :value="item.dicCode">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
    </v-table>
    <el-form
      :model="formData"
      label-position="top"
      ref="orderForm"
      :rules="rules"
    >
      <!-- <el-form-item v-if="approveLevel === '1'" label="商品是否需要寄回：" prop="isSendBack">
        <el-radio-group @change="changeSend" v-model="formData.isSendBack">
          <el-radio
            :disabled="true"
            v-for="item in sendBackList"
            :key="item.dicCode"
            :label="item.dicCode"
          >
            {{ item.dicName }}
          </el-radio>
        </el-radio-group>
      </el-form-item> -->
      <el-form-item
        v-if="checkShow(approveLevel, isShowItem)"
        style="margin-top: 10px"
        label="商品寄回方式："
        prop="returnMethod"
      >
        <el-radio-group v-model="formData.returnMethod">
          <el-radio
            v-for="item in lookupItems.RETURNMETHOD"
            :key="item.dicCode"
            :label="item.dicCode"
          >
            {{ item.dicName }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="checkShow(approveLevel, isShowItem)" label="运费承担方：" prop="undertaker">
        <el-radio-group
          @change="undertakerChange"
          v-model="formData.undertaker"
        >
          <el-radio label="用户">用户</el-radio>
          <el-radio label="福特方">福特方</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注：" prop="remarks">
        <el-input type="textarea" v-model="formData.remarks"></el-input>
      </el-form-item>
    </el-form>
    <div style="margin-top: 20px;" v-if="approveLevel === '2'">
      请注意，点击【确定】后，审批同意的商品将会进入重新发货流程
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose" class="white-btn">取消</el-button>
      <el-button @click="onSubmit" :loading="submitting" class="search-btn">
        确定
      </el-button>
    </span>
  </el-dialog>
</template>
<script>
import Vue from 'vue'
import VTable from '@/components/PageTable/index'
import { USERNAME, USERID } from '@/config/variableInit'
import { approvalExchange } from '@/api/order'
import { common } from '@/mixins/common'
import { mapGetters } from 'vuex'
export default {
  name: 'applyDialog',
  components: {
    VTable
  },
  props: {
    title: {
      type: String,
      default: String
    },
    refundId: {
      type: Number,
      default: Number
    },
    swapOrderId: {
      type: Number,
      default: Number
    },
    selectList: {
      type: Array
    }
  },
  mixins: [common],
  computed: {
    ...mapGetters(['lookupItems'])
  },
  mounted () {
    this.userName = Vue.ls.get(USERNAME)
    this.userId = Vue.ls.get(USERID)
  },
  data () {
    return {
      userName: '',
      checkStatus: '',
      auditRecordVo: {},
      itemVoList: [],
      userIf: '',
      isShow: false,
      swapTableData: [],
      formData: {
        // isSendBack: '',
        returnMethod: '',
        undertaker: '',
        remarks: ''
      },
      sendBackList: [
        {
          dicCode: '1',
          dicName: '是'
        },
        {
          dicCode: '0',
          dicName: '否'
        }
      ],
      submitting: false,
      rules: {
        // isSendBack: [
        //   { required: true, message: '请确认是否寄回商品', trigger: 'change' }
        // ],
        returnMethod: [
          { required: false, message: '请选择商品寄回方式', trigger: 'change' }
        ],
        undertaker: [
          {
            required: false,
            message: '请选择一个运费承担方',
            trigger: 'change'
          }
        ],
        remarks: [{ required: true, message: '备注不能为空', trigger: 'blur' }]
      },
      isShowItem: true,
      approveLevel: ''
    }
  },
  created () {},
  methods: {
    initData (type) {
      if (type) {
        if (type === '1') {
          this.formData = {
            // isSendBack: '1',
            returnMethod: '1',
            undertaker: '用户',
            remarks: ''
          }
        } else if (type === '2') {
          this.formData = {
            // isSendBack: '1',
            returnMethod: '2',
            undertaker: '用户',
            remarks: ''
          }
        }
      } else {
        this.formData = {
          // isSendBack: '1',
          returnMethod: '1',
          undertaker: '用户',
          remarks: ''
        }
      }
    },
    undertakerChange (val) {
    },
    handleClose () {
      this.isShow = false
      this.formData = {
        returnMethod: '1',
        undertaker: '用户',
        remarks: ''
      }
      this.swapTableData.forEach(item => {
        item.results = ''
      })
      this.approveLevel = ''
      this.isShowItem = true
    },
    checkShow (level, results) {
      let flag = true
      if (level === '1' && !results) {
        flag = false
      } else {
        if (level === '2') {
          flag = false
        } else {
          flag = true
        }
      }
      return flag
    },
    resultsChange () {
      const valArr = []
      this.swapTableData.forEach(item => {
        valArr.push(item.results)
      })
      this.isShowItem = valArr.some(item => {
        return item === '1'
      })
      // this.isShowItem = true
    },
    open (swapData, datas, swapLevel) {
      this.isShow = true
      this.approveLevel = swapLevel
      this.swapTableData = swapData
      this.initData(datas.deliveryMethod)
    },
    fetchRelationList () {
      this.$emit('fetchRelationList')
    },
    isAllEqual (array) {
      if (array.length > 0) {
        return array.every(function (value) {
          return value === '1' || value === '2'
        })
      }
    },
    onSubmit () {
      this.auditRecordVo = {}
      this.itemVoList = []
      this.$refs.orderForm.validate((vaild) => {
        if (vaild) {
          const resultsArr = []
          // 问题处理位置
          this.swapTableData.forEach(item => {
            resultsArr.push(item.results)
            this.itemVoList.push(item)
          })
          if (this.isAllEqual(resultsArr)) {
            this.submitting = true
            this.auditRecordVo = {
              freightBuyer: this.checkShow(this.approveLevel, this.isShowItem) ? this.formData.undertaker : '',
              operationId: this.userId,
              operationName: this.userName,
              remark: this.formData.remarks
            }

            const params = {
              itemVoList: this.itemVoList,
              auditRecordVo: this.auditRecordVo,
              orderId: this.swapOrderId,
              returnMethod: this.checkShow(this.approveLevel, this.isShowItem) ? this.formData.returnMethod : '',
              approveLevel: this.approveLevel

            }
            approvalExchange(params).then((res) => {
              this.pageLoading = false
              if (res) {
                if (Number(res.code) === 1) {
                  this.$alert('操作成功')
                  this.handleClose()
                } else if (res.code === 'ORDER_ORDER_0003') {
                  this.$alert('库存不足审核失败！', {
                    center: true,
                    showClose: false
                  })
                } else {
                  this.$confirm(res.code, {
                    confirmButtonText: '确定',
                    showCancelButton: false,
                    callback: (action) => {
                      this.fetchRelationList(this.swapOrderId)
                    }
                  })
                }
                this.submitting = false
              }
              this.handleClose()
              this.fetchRelationList(this.swapOrderId)
            })
          } else {
            this.$alert('请选择审核结果', {
              showCancelButton: false,
              confirmButtonText: '确定'
            })
          }
        }
      })
    }
  }
}
</script>
